/**
  * <br>JAVACC DEMO 1.0<br>
  * @copy right dwusoft company All rights reserved.<br>
  * <br>
  * @Package com.dwusoft.platform.interceptor
*/
package com.dwusoft.platform.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.exception.DaoAccessException;
import com.apache.exception.BusinessException;
import com.apache.exception.ServiceException;

/**
  * description: 统一异常处理器
  * @author Hou DaYu 创建时间：上午10:38:24
  */
public class UnityExceptionResolver implements HandlerExceptionResolver {

	private Logger log = Logger.getLogger("Errors");

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		String requestInfo = "URL:" + request.getRequestURI();
		requestInfo += " Query:" + request.getQueryString();
		String header = request.getHeader("X-Requested-With");
		boolean isAjax = "XMLHttpRequest".equals(header) ? true : false;
		String message = "系统运行异常！";
		// 根据不同错误转向不同页面  
		if (ex instanceof DaoAccessException) {
			writeLog(ex, requestInfo);
			message = "数据库操作异常！";
		} else if (ex instanceof BusinessException) {
			writeLog(ex, requestInfo);
			message = "业务方法执行异常！";
		} else if (ex instanceof ServiceException) {
			writeLog(ex, requestInfo);
			message = "service调用异常！";
		} else {
			writeLog(ex, requestInfo);
		}
		if (isAjax) {//ajax请求
			response.setContentType("text/html;charset=utf-8");
			try {
				PrintWriter writer = response.getWriter();
				writer.write(message);
				writer.flush();
				writer.close();
			} catch (IOException e) {
			}
			return new ModelAndView();
		} else {//正常请求
			request.setAttribute("errors", message);
			return new ModelAndView("error/error");
		}
	}

	/**
	 * 打印错误日志
	 */
	private void writeLog(Exception ex, String requestInfo) {
		String usagePatterns = Validator.getDefaultStr(SystemTools.getInstance().getValue("usage_patterns"), "1");
		if ("1".equals(usagePatterns)) {
			String msg = "ZBXSOFT CASE: error{ " + ex.getMessage() + " }; \n" + " request{ " + requestInfo + " }";
			log.error(msg);
		} else {
			ex.printStackTrace();
			log.error(ex);
		}
	}
}
